package com.bolt.auth.security.auth.server.service.impl;

import com.bolt.auth.security.auth.server.service.ValidateCodeService;
import com.bolt.auth.security.common.exception.VerificationCodeException;
import com.bolt.auth.security.common.properties.BoltSecurityProperties;
import com.bolt.common.utils.StrUtil;
import com.bolt.convention.data.ResultMessage;
import com.bolt.convention.data.Results;
import com.bolt.support.cache.redis.RedisManager;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private BoltSecurityProperties boltSecurityProperties;

    @Override
    public void putCode(String deviceId, String code, long time) {
        redisManager.cache(deviceId,code,time, TimeUnit.MINUTES);
    }

    public ResultMessage createImageCode(){
        Map<String, Object> resultMap = new HashMap<>(2);
        String uuid = UUID.randomUUID().toString();
        Captcha captcha = boltSecurityProperties.getCaptcha();
        resultMap.put("graphId", uuid);
        resultMap.put("img", captcha.toBase64());
        putCode(uuid, captcha.text(), boltSecurityProperties.getCaptchaCode().getExpiration());
        return Results.success(resultMap);
    }

    /**
     * 获取验证码
     *
     * @param deviceId 前端唯一标识/手机号
     */
    @Override
    public String getCode(String deviceId) {
        return redisManager.get(deviceId);
    }

    /**
     * 删除验证码
     *
     * @param deviceId 前端唯一标识/手机号
     */
    @Override
    public void removeCode(String deviceId) {
        redisManager.del(deviceId);
    }

    /**
     * 验证验证码
     *
     * @param deviceId
     * @param validCode
     */
    @Override
    public void validateCode(String deviceId, String validCode) {
        if (StrUtil.isBlank(deviceId)) {
            throw new VerificationCodeException("请在请求参数中携带deviceId参数");
        }
        String code = this.getCode(deviceId);
        if (StrUtil.isBlank(validCode)) {
            throw new VerificationCodeException("请填写验证码");
        }

        if (code == null) {
            throw new VerificationCodeException("验证码不存在或已过期");
        }

        if (!StrUtil.equals(code, validCode.toLowerCase())) {
            throw new VerificationCodeException("验证码不正确");
        }

        this.removeCode(deviceId);
    }
}

 